import { useState } from 'react';
import {
    Form, Input, InputNumber, Select, Upload, Button,
    message, Card, Space, Typography, Row, Col, Image
} from 'antd';
import {
    PlusOutlined, SaveOutlined, EyeOutlined, InfoOutlined,
    MinusOutlined, CheckCircleOutlined
} from '@ant-design/icons';

const { TextArea } = Input;
const { Title, Text } = Typography;

// 图片上传最大数量限制
const MAX_DETAIL_IMAGES = 5; // 详细图片最多5张
const MAX_COVER_IMAGES = 1;   // 封面图片最多1张

// 获取Base64图片
const getBase64 = file =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

// 图片上传前的校验
const beforeUpload = (file, maxSize = 5) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式的图片!');
        return false;
    }

    const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
    if (!isLtMaxSize) {
        message.error(`图片大小不能超过${maxSize}MB!`);
        return false;
    }

    return true;
};

export const AddProduct = () => {
    // 状态管理 - 修改规格列表结构，增加价格字段
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([]);
    const [coverFileList, setCoverFileList] = useState([]); // 封面图片列表
    // 每个规格项包含id、规格值和对应价格
    const [specsList, setSpecsList] = useState([{ id: Date.now(), spec: '', price: 0 }]);
    const [previewOpen, setPreviewOpen] = useState(false);

    // 产品类型数据
    const productTypes = [
        { id: '1', name: '理疗项目' },
        { id: '2', name: '中药产品' },
        { id: '3', name: '养生器材' },
        { id: '4', name: '保健饮品' },
        { id: '5', name: '定制套餐' }
    ];

    // 添加新的规格输入框（包含价格）
    const addSpecs = () => {
        setSpecsList([...specsList, { id: Date.now(), spec: '', price: 0 }]);
    };

    // 移除规格输入框
    const removeSpecs = (id) => {
        if (specsList.length <= 1) return; // 至少保留一个
        setSpecsList(specsList.filter(item => item.id !== id));
    };

    // 处理规格值变化
    const handleSpecChange = (id, value) => {
        const newList = specsList.map(item =>
            item.id === id ? { ...item, spec: value } : item
        );
        setSpecsList(newList);
        // 更新表单中的规格值为数组形式
        form.setFieldsValue({
            P_Specs: newList.map(item => ({spec: item.spec, price: item.price})).filter(item => item.spec)
        });
    };

    // 处理规格价格变化
    const handleSpecPriceChange = (id, value) => {
        const newList = specsList.map(item =>
            item.id === id ? { ...item, price: value } : item
        );
        setSpecsList(newList);
        // 更新表单中的规格值为数组形式
        form.setFieldsValue({
            P_Specs: newList.map(item => ({spec: item.spec, price: item.price})).filter(item => item.spec)
        });
    };

    // 处理图片预览
    const handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };

    // 处理详细图片上传变化
    const handleDetailImageChange = ({ fileList: newFileList }) => {
        // 过滤掉已移除的文件
        const filteredList = newFileList.filter(file => file.status !== 'removed');
        setFileList(filteredList);
    };

    // 处理封面图片上传变化
    const handleCoverImageChange = ({ fileList: newFileList }) => {
        // 过滤掉已移除的文件并限制数量
        const filteredList = newFileList
            .filter(file => file.status !== 'removed')
            .slice(0, MAX_COVER_IMAGES); // 只保留第一张
        setCoverFileList(filteredList);
    };

    // 上传按钮通用组件
    const renderUploadButton = (text, icon = <PlusOutlined />) => (
        <button style={{ border: 0, background: 'none' }} type="button">
            {icon}
            <div style={{ marginTop: 8 }}>{text}</div>
        </button>
    );

    // 处理提交
    const handleSubmit = async () => {
        try {
            setLoading(true);
            const values = await form.validateFields();

            // 处理图片数据
            const coverImage = coverFileList.length > 0 ?
                coverFileList[0].response?.url : '';

            const detailImages = fileList.map(file =>
                file.response?.url
            ).filter(Boolean);

            // 处理规格数据 - 确保是数组形式，包含规格和价格
            const formData = {
                ...values,
                P_IsService: 1, // 所有产品默认是服务类，固定值1
                P_CoverImage: coverImage, // 封面图
                P_DetailImages: detailImages, // 详细图数组
                // 整理规格和价格数据
                P_Specs: specsList
                    .map(item => ({ spec: item.spec, price: item.price }))
                    .filter(item => item.spec && item.price !== null && item.price !== undefined)
            };

            // 模拟API提交
            console.log('提交产品数据:', formData);

            // 实际应用中这里会调用API
            setTimeout(() => {
                message.success('产品添加成功！');
                setLoading(false);
                form.resetFields();
                setFileList([]);
                setCoverFileList([]);
                setSpecsList([{ id: Date.now(), spec: '', price: 0 }]);
            }, 800);

        } catch (errorInfo) {
            message.error('表单填写有误，请检查后重试');
            setLoading(false);
        }
    };


    return (
        <>
            <div className="modal-box">
                <Text type="secondary" style={{ marginBottom: 20, display: 'block', fontSize: '13px' }}>
                    请填写产品信息，带 <span style={{ color: '#ff4d4f' }}>*</span> 为必填项
                </Text>

                <Form
                    form={form}
                    layout="vertical"
                    scrollToFirstError
                    initialValues={{
                        P_IsService: 1, // 初始化默认是服务类产品（值为1）
                        P_Specs: [] // 初始化为空数组
                    }}
                >
                    
                    {/* 媒体信息卡片 - 封面图和详细图分开上传 */}
                    <Card
                        style={{
                            marginBottom: 20,
                            borderRadius: '8px',
                            borderColor: '#e8e8e8',
                            boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
                              borderLeft: '3px solid #1890ff'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            marginBottom: 16,
                            color: '#1f2329'
                        }}>
                            <EyeOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            <Title level={5} style={{ margin: 0 }}>媒体信息</Title>
                        </div>

                        {/* 封面图片上传区域 */}
                        <Form.Item
                            name="P_CoverImage"
                            label={
                                <span>
                                    封面图片 <span style={{ color: '#ff4d4f' }}>*</span>
                                </span>
                            }
                            rules={[{ required: true, message: '请上传产品封面图片' }]}
                            labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }}
                            style={{ marginBottom: 24 }}
                        >
                            <div>
                                <Text type="secondary" style={{ fontSize: '13px', marginBottom: 12, display: 'block' }}>
                                    封面图：请上传一张清晰的产品主图，将作为产品展示的主要图片
                                </Text>
                                <Upload
                                    action="http://116.62.217.197:9921/api/Upload/Upload_Goods_Cover"
                                    listType="picture-card"
                                    fileList={coverFileList}
                                    onPreview={handlePreview}
                                    onChange={handleCoverImageChange}
                                    beforeUpload={(file) => beforeUpload(file)}
                                    maxCount={MAX_COVER_IMAGES}
                                >
                                    {coverFileList.length >= MAX_COVER_IMAGES ? null : renderUploadButton('上传封面')}
                                </Upload>
                            </div>
                        </Form.Item>

                        {/* 详细图片上传区域 */}
                        <Form.Item
                            name="P_DetailImages"
                            label="产品详细图片"
                            rules={[{ required: true, message: '请至少上传一张产品详细图片' }]}
                            labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }}
                        >
                            <div>
                                <Text type="secondary" style={{ fontSize: '13px', marginBottom: 12, display: 'block' }}>
                                    详细图：最多上传{MAX_DETAIL_IMAGES}张图片，展示产品细节、使用场景等
                                </Text>
                                <Upload
                                    listType="picture-card"
                                    action="http://116.62.217.197:9921/api/Upload/Upload_Goods_Cover"
                                    fileList={fileList}
                                    onPreview={handlePreview}
                                    onChange={handleDetailImageChange}
                                    beforeUpload={(file) => beforeUpload(file)}
                                    maxCount={MAX_DETAIL_IMAGES}
                                >
                                    {fileList.length >= MAX_DETAIL_IMAGES ? null : renderUploadButton('上传图片')}
                                </Upload>
                                {/* 图片预览组件 */}
                                {previewImage && (
                                    <Image
                                        wrapperStyle={{ display: 'none' }}
                                        preview={{
                                            visible: previewOpen,
                                            onVisibleChange: visible => setPreviewOpen(visible),
                                            afterOpenChange: visible => !visible && setPreviewImage(''),
                                        }}
                                        src={previewImage}
                                    />
                                )}
                            </div>
                        </Form.Item>
                    </Card>
                    {/* 基本信息卡片 */}
                    <Card
                        style={{
                            marginBottom: 20,
                            borderRadius: '8px',
                            borderColor: '#e8e8e8',
                            boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
                              borderLeft: '3px solid #1890ff'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            marginBottom: 16,
                            color: '#1f2329'
                        }}>
                            <InfoOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            <Title level={5} style={{ margin: 0 }}>基本信息</Title>
                        </div>

                        <Row gutter={[16, 16]}>
                            <Col xs={24} sm={12}>
                                <Form.Item
                                    name="P_Name"
                                    label="产品名称"
                                    rules={[{ required: true, message: '请输入产品名称' }, { max: 200, message: '名称不能超过200个字符' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <Input
                                        placeholder="请输入产品名称"
                                        style={{ borderRadius: '6px' }}
                                    />
                                </Form.Item>
                            </Col>

                            <Col xs={24} sm={12}>
                                <Form.Item
                                    name="P_TypeID"
                                    label="产品类型"
                                    rules={[{ required: true, message: '请选择产品类型' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <Select
                                        placeholder="请选择产品类型"
                                        style={{ width: '100%', borderRadius: '6px' }}
                                    >
                                        {productTypes.map(type => (
                                            <Select.Option key={type.id} value={type.id}>
                                                {type.name}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Col>
                         
                            <Col xs={24}>
                                {/* 修改规格部分，增加价格输入 */}
                                <Form.Item
                                    name="P_Specs"
                                    label="产品规格及对应价格"
                                    rules={[
                                        { required: true, message: '请至少输入一个规格及对应价格' },
                                    ]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <div>
                                        {specsList.map((item, index) => (
                                            <div key={item.id} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                                                <Input
                                                    placeholder={`请输入规格 ${index + 1}`}
                                                    style={{ borderRadius: '6px', marginRight: 8, flex: 1 }}
                                                    value={item.spec}
                                                    onChange={(e) => handleSpecChange(item.id, e.target.value)}
                                                />
                                                <InputNumber
                                                    placeholder="请输入价格"
                                                    style={{ borderRadius: '6px', marginRight: 8, width: 180 }}
                                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                                    parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                                                    precision={2}
                                                    min={0}
                                                    value={item.price}
                                                    onChange={(value) => handleSpecPriceChange(item.id, value)}
                                                />
                                                {specsList.length > 1 && (
                                                    <Button
                                                        icon={<MinusOutlined />}
                                                        size="small"
                                                        onClick={() => removeSpecs(item.id)}
                                                        style={{ color: '#ff4d4f' }}
                                                    />
                                                )}
                                            </div>
                                        ))}
                                        <Button
                                            type="dashed"
                                            icon={<PlusOutlined />}
                                            onClick={addSpecs}
                                            style={{ marginTop: 8, width: '100%' }}
                                        >
                                            添加规格及价格
                                        </Button>
                                    </div>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card>

                    {/* 服务详情卡片 */}
                    <Card
                        style={{
                            marginBottom: 20,
                            borderRadius: '8px',
                            borderColor: '#e8e8e8',
                            boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
                            borderLeft: '3px solid #1890ff'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            marginBottom: 16,
                            color: '#1f2329'
                        }}>
                            <InfoOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            <Title level={5} style={{ margin: 0 }}>服务详情（必填）</Title>
                        </div>

                        <Row gutter={[16, 16]}>
                            <Col xs={24}>
                                <Form.Item
                                    name="PSD_Effect"
                                    label="服务功效"
                                    rules={[{ required: true, message: '请输入服务功效' }, { max: 225, message: '功效不能超过225个字符' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <Input
                                        placeholder="请输入服务功效，如：缓解疲劳、疏通经络、暖宫驱寒等"
                                        style={{ borderRadius: '6px' }}
                                    />
                                </Form.Item>
                            </Col>

                            <Col xs={24}>
                                <Form.Item
                                    name="PSD_Attention"
                                    label="注意事项"
                                    rules={[{ required: true, message: '请输入注意事项' }, { max: 225, message: '注意事项不能超过225个字符' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <TextArea
                                        rows={3}
                                        placeholder="请输入服务的注意事项，如：孕妇慎用、饭后1小时内不宜进行、皮肤破损者禁用等"
                                        style={{
                                            borderRadius: '6px',
                                            resize: 'vertical'
                                        }}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card>


                    {/* 描述信息卡片 */}
                    <Card
                        style={{
                            marginBottom: 20,
                            borderRadius: '8px',
                            borderColor: '#e8e8e8',
                            boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
                              borderLeft: '3px solid #1890ff'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            marginBottom: 16,
                            color: '#1f2329'
                        }}>
                            <InfoOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            <Title level={5} style={{ margin: 0 }}>产品描述</Title>
                        </div>

                        <Row gutter={[16, 16]}>
                            <Col xs={24}>
                                <Form.Item
                                    name="P_Description"
                                    label="详细描述"
                                    rules={[{ required: true, message: '请输入产品描述' }, { max: 2000, message: '描述不能超过2000个字符' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <TextArea
                                        rows={5}
                                        placeholder="请输入产品详细描述"
                                        style={{
                                            borderRadius: '6px',
                                            resize: 'vertical'
                                        }}
                                    />
                                </Form.Item>
                            </Col>

                            <Col xs={24}>
                                <Form.Item
                                    name="P_Remark"
                                    label="备注信息"
                                    rules={[{ max: 500, message: '备注不能超过500个字符' }]}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <TextArea
                                        rows={2}
                                        placeholder="请输入产品备注信息"
                                        style={{
                                            borderRadius: '6px',
                                            resize: 'vertical'
                                        }}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card>

                    {/* 操作按钮 */}
                    <div style={{
                        marginTop: 20,
                        textAlign: 'right',
                        paddingTop: 16,
                        borderTop: '1px solid #e8e8e8'
                    }}>
                        <Space size="middle">
                            <Button
                                type="primary"
                                icon={<SaveOutlined />}
                                onClick={handleSubmit}
                                loading={loading}
                                style={{
                                    borderRadius: '6px',
                                    padding: '6px 16px',
                                    boxShadow: '0 2px 4px rgba(24, 144, 255, 0.2)'
                                }}
                            >
                                保存产品
                            </Button>
                        </Space>
                    </div>
                </Form>
            </div>
        </>
    );
};

export default AddProduct;
